`timescale 1ns / 1ps
//////////////////////////////////////////////////////////////////////////////////
// Company: 
// Engineer: 
// 
// Create Date:    18:36:45 10/28/2014 
// Design Name: 
// Module Name:    Rx 
// Project Name: 
// Target Devices: 
// Tool versions: 
// Description: 
//
// Dependencies: 
//
// Revision: 
// Revision 0.01 - File Created
// Additional Comments: 
//
//////////////////////////////////////////////////////////////////////////////////
module Rx(input data, input tick, output reg [7:0] Data_Out, output reg rx_done
    );


//Declaracion de estados
localparam [3:0]  IDLE = 4'b0001,
						START = 4'b0010,
						DATA = 4'b0100,
						STOP = 4'b1000;

//Declaración de señales (las utilizare para el elemento de memoria por lo tanto son tipo REGISTRO)
reg[3:0] current_state, next_state;
reg [3:0] tick_counter;
reg [3:0] n;		//Posicion dentro del arreglo interno de datos
reg [7:0] buffer;

//Registro de estado (Memoria)
always @(posedge tick) begin
	current_state = next_state;
end
		
//Logica de cambio de estado						
always @*
begin
	
	case(current_state)
		IDLE:
			begin
				
				//Data_Out = 0;
				rx_done = 0;
				buffer = 0;
				if(data == 0) begin //Bit de start
					tick_counter = 0; //Iniciar Contador
					next_state = START;
				end
			end
		START:
			begin
				
				Data_Out = 0;
				rx_done = 0;
				if(tick == 1) begin //Tick en 1
					if(tick_counter == 7) begin //Llegar a la mitad del bit recibido
						tick_counter = 0 ; //Reiniciar contador
						n = 0;				//Posicion dentro del bffer de salida
						next_state = DATA;
					end
					else
						tick_counter = tick_counter + 1; //Hasta llegar a 7
				end
			end
		DATA:
			begin
				
				Data_Out = buffer;
				rx_done = 0; 
				if(tick == 1) begin
					if(tick_counter == 15) begin
						tick_counter = 0;
						buffer[n] = data;
						if(n == 7) next_state = STOP;
						else n = n + 1;
					end
					else tick_counter = tick_counter + 1; //Hasta llegar a 15
				end
			end
		
		STOP:
			begin
				Data_Out = buffer;
				rx_done = 1; //aca iba 0 en vez de 1, se lo cambie
				
				if(tick == 1) begin
					if(tick_counter == 15) begin
						tick_counter = 0;
						//rx_done = 1;
						next_state = IDLE;
					end
					else tick_counter = tick_counter + 1;
				end
			end
			
		default:
			begin
				rx_done = 0;
				Data_Out = 0;
				
				next_state = IDLE;
				buffer = 0;
			end
	endcase
					
end

endmodule
//tuto, ya sabemos q hace 28-10.2014